package com.example.jiangkt.ergongyi.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.jiangkt.ergongyi.R;
import com.example.jiangkt.ergongyi.service.BackstageService;
import com.example.jiangkt.ergongyi.util.AlertShow;
import com.example.jiangkt.ergongyi.util.CustomAction;
import com.example.jiangkt.ergongyi.util.UserUtil;

import java.util.HashMap;


public class LoginActivity extends Activity implements View.OnClickListener {
    private EditText et_email;
    private EditText et_userpwd;
    private Button bt_forget;
    private Button bt_add_user;
    private Button bt_login;
    private ImageView iv_cancel;
    private TextView tv_login_warn;

    private Button bt_save_login;
    private Button bt_other_login;
    private EditText et_other_email;
    private EditText et_other_userpwd;
    private TextView tv_other_warn;

    private String otherEmail = "";
    private String otherUserPwd = "";

    private Intent serviceIntent;
    private LoginReceiver loginReceiver;
    private LinearLayout other_user_login;
    private AlertDialog otherLoginDialog;
    private String username;
    private String password;


    private String userEmail;
    private String userPwd;
    private JSONObject jsonObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        this.init();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (otherLoginDialog!=null){
            otherLoginDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (otherLoginDialog!=null){
            otherLoginDialog.dismiss();
        }
        this.unregisterReceiver(loginReceiver);
    }

    private void init() {
        serviceIntent = new Intent(this, BackstageService.class);
        this.startService(serviceIntent);

        /**
         * 绑定用户名和用户密码输入框
         */
        et_email = findViewById(R.id.lg_et_email);
        et_userpwd = findViewById(R.id.lg_et_userpwd);
        tv_login_warn = findViewById(R.id.tv_login_warn);
        tv_login_warn.setTextColor(getApplication().getResources().getColor(R.color.colorLogin1));
        bt_forget = findViewById(R.id.lg_bt_forget);
        bt_add_user = findViewById(R.id.lg_bt_adduser);
        bt_login = findViewById(R.id.lg_bt_login);
        bt_login.setOnClickListener(this);
        bt_forget.setOnClickListener(this);
        bt_add_user.setOnClickListener(this);
        bt_login.setOnClickListener(this);

        //获取保存在手机里的邮箱和密码
        SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
        other_user_login = (LinearLayout) LoginActivity.this.getLayoutInflater().inflate(R.layout.other_user_login, null);
        bt_save_login = other_user_login.findViewById(R.id.bt_save_login);
        bt_save_login.setOnClickListener(this);
        bt_other_login = other_user_login.findViewById(R.id.bt_other_login);
        bt_other_login.setOnClickListener(this);
        et_other_email = other_user_login.findViewById(R.id.lg_other_email);
        et_other_userpwd = other_user_login.findViewById(R.id.lg_other_userpwd);
        tv_other_warn = other_user_login.findViewById(R.id.tv_other_warn);
        tv_other_warn.setTextColor(getApplication().getResources().getColor(R.color.colorLogin1));
        if (sharedPre != null) {
            username = sharedPre.getString("username", "");
            password = sharedPre.getString("password", "");
            if (!"".equals(username) && !"".equals(password)) {
                // 用户名和密码的输入框控件
                et_email.setText(username);
                et_userpwd.setText(password);
                et_email.setEnabled(false);
                et_userpwd.setEnabled(false);

                otherLoginDialog = new AlertDialog.Builder(this)
                        .setView(other_user_login)
                        .create();
                otherLoginDialog.show();
                DisplayMetrics dm = new DisplayMetrics();
                //获取屏幕信息
                this.getWindowManager().getDefaultDisplay().getMetrics(dm);

                int screenWidth = dm.widthPixels;

                int screenHeigh = dm.heightPixels;
                WindowManager.LayoutParams params =

                        otherLoginDialog.getWindow().getAttributes();//获取dialog信息

                params.width = screenWidth - 20;

                params.height = screenHeigh / 2;

                otherLoginDialog.getWindow().setAttributes(params);//设置大小
//            other_user_login.setBackground(getApplication().getResources().getDrawable(R.drawable.lunch_pop_bg));
                iv_cancel = other_user_login.findViewById(R.id.other_login_cancel);
                iv_cancel.setOnClickListener(this);
            }

        }

        IntentFilter filter = new IntentFilter(CustomAction.LOGIN_ACTION);
        loginReceiver = new LoginReceiver();
        registerReceiver(loginReceiver, filter);

    }

    private boolean login(String email, String userPwd) {
        try {
            if (!AlertShow.isEmail(email)) {
                tv_other_warn.setText("邮箱地址不符合");
                Toast.makeText(this,"邮箱地址不符合",Toast.LENGTH_SHORT).show();
                //不是加密过的字符串解密会报错
                //如果输入的密码符合正则表达式密码，则返回false，不执行&&后面语句，所以该代码正确
            } else if (!AlertShow.isPassword(userPwd)&&!AlertShow.isPassword(UserUtil.decrypt(userPwd))) {
                tv_other_warn.setText("密码不符合");
                Toast.makeText(this,"密码不符合",Toast.LENGTH_SHORT).show();
            } else {
                return true;
            }

        }catch (Exception e){
            tv_other_warn.setText("密码不符合");
            Toast.makeText(this,"密码不符合",Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            finish();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lg_bt_forget:
                startActivity(new Intent(this, UpUserActivity.class));
                finish();
                break;
            case R.id.lg_bt_adduser:
                startActivity(new Intent(this, AddUserActivity.class));
                finish();
                break;
            case R.id.lg_bt_login:
                if(login(et_email.getText().toString(),et_userpwd.getText().toString())) {
                    userEmail = et_email.getText().toString();
                    userPwd = et_userpwd.getText().toString();
                    AlertShow.dialog = ProgressDialog.show(this, null, "正在登录中...");
                    HashMap<Object, Object> loginMap = new HashMap<>();
                    loginMap.put("reqType", "loginReq");
                    loginMap.put("email", userEmail);
                    loginMap.put("userPwd", AlertShow.isPassword(userPwd) == true ? UserUtil.encrypt(userPwd) : userPwd);

                    Intent loginIntent = new Intent(CustomAction.SERVICE_ACTION);
                    loginIntent.putExtra("request", JSONObject.toJSON(loginMap).toString());
                    sendBroadcast(loginIntent);
                }
                break;
            case R.id.bt_save_login:
                AlertShow.dialog = ProgressDialog.show(this, null, "正在登录中...");
                HashMap<Object, Object> saveLoginMap = new HashMap<>();
                saveLoginMap.put("reqType", "loginReq");
                saveLoginMap.put("email", et_email.getText().toString());
                saveLoginMap.put("userPwd", et_userpwd.getText().toString());

                Intent saveLoginIntent = new Intent(CustomAction.SERVICE_ACTION);
                saveLoginIntent.putExtra("request", JSONObject.toJSON(saveLoginMap).toString());
                sendBroadcast(saveLoginIntent);
                break;
            case R.id.bt_other_login:
                otherEmail = et_other_email.getText().toString();
                otherUserPwd = et_other_userpwd.getText().toString();
                if (login(otherEmail, otherUserPwd)) {
                    AlertShow.dialog = ProgressDialog.show(this, null, "正在登录中...");
                    HashMap<Object, Object> otherMap = new HashMap<>();
                    otherMap.put("reqType", "loginReq");
                    otherMap.put("email", otherEmail);
                    otherMap.put("userPwd", UserUtil.encrypt(otherUserPwd));

                    Intent otherIntent = new Intent(CustomAction.SERVICE_ACTION);
                    otherIntent.putExtra("request", JSONObject.toJSON(otherMap).toString());
                    sendBroadcast(otherIntent);
                }
                break;
            case R.id.other_login_cancel:
                otherLoginDialog.cancel();
                break;
        }
    }

    public class LoginReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String respType = intent.getStringExtra("login");

            if ("301".equals(respType)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                tv_other_warn.setText("该邮箱未注册");
                Toast.makeText(LoginActivity.this,"该邮箱未注册",Toast.LENGTH_SHORT).show();
            } else if ("302".equals(respType)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                tv_other_warn.setText("用户已登录");
                Toast.makeText(LoginActivity.this,"用户已登录",Toast.LENGTH_SHORT).show();
            } else if ("303".equals(respType)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                tv_other_warn.setText("密码错误");
                Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_SHORT).show();
            } else if ("305".equals(respType)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                String userInfo = intent.getStringExtra("userInfo");
                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                if("".equals(username)&&"".equals(password)){
                    UserUtil.saveLoginInfo(LoginActivity.this, userEmail, UserUtil.encrypt(userPwd));
                }
                Bundle data = new Bundle();
                data.putSerializable("userInfo", userInfo);
                jsonObject = JSONObject.parseObject(userInfo);
                data.putSerializable("userId",jsonObject.getString("userId"));
                data.putSerializable("userName",jsonObject.getString("userName"));
                data.putSerializable("roomKey",jsonObject.getString("roomKey"));
                Intent startActivity = new Intent(LoginActivity.this, UserInfoActivity.class);
                startActivity.putExtras(data);
                LoginActivity.this.startActivity(startActivity);
                LoginActivity.this.finish();
            }
        }
    }
}
